define(function(require, exports){
	var pubjs = require('pubjs');
	var $ = require('jquery');
	var view = require('@base/view');
	var util = require('util');

	var Client = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'reqType': 'websocket'
				,'url': 'spot/rtbDomainList'
				,'urlCheck': 'spot/rtbDomainCheck'
				,'readonly': false
				,'view_model': {
					'selected': false
					,operator : [
						{'name': LANG('添加要指派的客户'), 'id': 'add'}
					]
					,value: []
					,operateEvent: this.vmOperateEvent.bind(this)
				}
			});

			this.$ids = '';	//保存已经选择的媒体域名id集合.
			this.$param = {};

			this.Super('init', arguments);
		}
		,afterBuild: function() {
			var self = this;
			var c = self.getConfig();
			self.append($([
				'<div class="P-dealClientGrid">'
					,'<div class="operate mb10 tr">'
						,'<button class="btn btn-default ml10" ms-repeat-op="operator" ms-click="operateEvent(op.id)">{{op.name}}</button>'
					,'</div>'
					,'<div pub-name="grid" pub-mod="deal/grid/edit.client"/>'
				,'</div>'

			].join('')));

			var config = {
				'grid': {
					'readonly': c.readonly
				}
			};

			self.buildFromTemplate(config)
		}
		,vmOperateEvent: function(type) {
			switch (type) {
				case 'add':
					this.showPop();
					break;
			}
		}
		/*
		 批量导入导出方法
		 */
		,showPop: function() {
			var self = this;
			var mod = self.$.pop;
			var ids = this.getValue();
			if(!mod) {
				this.createAsync('pop',"/project/modules/selectUser.selectCustomer", function(mod) {
					mod.show().setData(ids);
				})
			}
			else {
				mod.show().setData(ids);
			}
		}
		,setParam: function(param) {
			this.$param = $.extend(this.$param, param);
			this.$.grid.setParam(this.$param);
			return this;
		}
		,load: function() {
			this.$.grid.load();
			return this;
		}
		,reset: function() {
			this.$.grid.setData([]);
			return this;
		}
		,setValue: function(value) {
			this.$.grid.setData(value || []);
			return this;
		}
		,getValue: function() {
			var data = this.$.grid.getData();
			var ret = [];
			if(data && data.length) {
				util.each(data, function(item) {
					if(item.UserId) {
						ret.push(item.UserId);
					}
				})
			}

			return ret;
		}
		,onListOpClick:function(ev) {
			//删除单条记录
			var index = ev.param.index;
			this.$.grid.removeRow(index);
			return false;
		}
		,dataChange:function(ids){
			this.fire(
				"domainChange"
				,{
					"ids":ids || this.$ids
				}
			);
			ids = null;
			return this;
		}
		,onSelectCustomer: function(ev) {
			// 重新选择的用户信息
			var data = ev.param;
			// 已选则用户信息
			var items = this.$.grid.getData();
			var ids = [];
			// 缓存已选的用户id，后续做匹配
			util.each(items, function(item)
			{
				ids.push(item.UserId);
			});

			// 匹配已选用户，如果没有选，则push用户记录
			util.each(data, function(item)
			{
				if (ids.indexOf(item.UserId) == -1)
				{
					items.push(item);
				}
			});

			// 重新设置过滤后的用户用户信息
			this.setValue(items);
			return false;
		}
	});

	exports.client = Client;
});